//
//  ViewController.swift
//  10tableview
//
//  Created by Clover on 2018/4/19.
//  Copyright © 2018年 youbing. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var tableview: UITableView!
    override func viewDidLoad() {
        super.viewDidLoad()
        self.tableview.register(UINib.init(nibName: "mainCell", bundle: Bundle.main), forCellReuseIdentifier: "mainCell")
        self.tableview.tableFooterView = UIView.init()
        self.tableview.separatorStyle = UITableViewCellSeparatorStyle.none
    }
    
    override func viewWillAppear(_ animated: Bool) {
        self.animationTable()
    }
    
    func animationTable(){
        let cells = tableview.visibleCells
        let tableHeight = tableview.bounds.size.height

        for (index, cell) in cells.enumerated() {
            cell.transform = CGAffineTransform(translationX: 0, y: tableHeight)
            UIView.animate(withDuration: 0.8, delay: 0.05 * Double(index), usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: [], animations: {
                cell.transform = CGAffineTransform(translationX: 0, y: 0)
            }, completion: nil)
        }
    }
    
    func myTableviewReload() {
        self.tableview.reloadData()
        self.animationTable()
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        myTableviewReload()
    }
}

extension UIViewController : UITableViewDelegate,UITableViewDataSource{
    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 20;
    }
    
    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell : mainCell = tableView.dequeueReusableCell(withIdentifier: "mainCell", for: indexPath) as! mainCell
        cell.textLabel?.text = "11"
        cell.backgroundColor = colorforIndex(indexPath: indexPath)
        return cell
    }
    
    func colorforIndex(indexPath: IndexPath) -> UIColor {
        let index = indexPath.row
        let itemCount = 16
        let color = (CGFloat(index) / CGFloat(itemCount)) * 0.6
        return UIColor(red: 1.0, green: color, blue: 0.0, alpha: 1.0)
    }
    
}

